package com.yonyou.cyxdms.sysAuth.service.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yonyou.cyx.framework.util.http.RestHttpUtil;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.domains.vo.RegionVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonRegionService;
import com.yonyou.cyxdms.sysAuth.service.dto.LocationResultDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.DealerInfoPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.DealerInfoMapper;
import com.yonyou.cyxdms.sysAuth.service.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * BaiDuController
 *
 * @author LiJun
 * @Description
 * @date 2019/7/31 14:15
 */
@RequestMapping("/location")
@RestController
public class BaiDuController {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    private static final String URL = "http://api.map.baidu.com/geocoder/v2/?output=json&ak=crO4GfGoPVD0zgoEIgTAKO35pUTiKhGf&address=";
    private static final String URL2 = "http://api.map.baidu.com/geocoder/v2/?output=json&pois=1&ak=crO4GfGoPVD0zgoEIgTAKO35pUTiKhGf&location=";
    @Resource
    DealerInfoMapper dealerInfoMapper;

    @Autowired
    BaseCommonRegionService baseCommonRegionService;

    @Qualifier(value = "restTemplateNoLb")
    @Autowired
    RestTemplate restTemplate;


    @GetMapping("/get")
    public String getLocation() {
        LambdaQueryWrapper<DealerInfoPO> queryWrapper = new QueryWrapper<DealerInfoPO>().lambda();
        queryWrapper.isNull(DealerInfoPO::getLatitude).or().isNull(DealerInfoPO::getLongitude);
        queryWrapper.groupBy(DealerInfoPO::getDealerId);
        List<DealerInfoPO> list = dealerInfoMapper.selectList(queryWrapper);

        for (DealerInfoPO po : list) {
            try {
                String address = po.getAddress();
                if (StringUtils.isEmpty(address) || "null".equalsIgnoreCase(address)) {
                    address = po.getDealerName();
                }

                String response = RestHttpUtil.get(restTemplate, URL + address, String.class);

                logger.debug("DealerInfoPO={}\nBaiDuResponse={}", JSONUtil.objectToJson(po), response);

                HashMap jsonObject = JSON.parseObject(response, HashMap.class);
                HashMap result = JSON.parseObject(JSON.toJSONString(jsonObject.get("result")), HashMap.class);

                if (result != null && result.get("location") != null) {
                    LocationResultDTO location = JSON.parseObject(JSON.toJSONString(result.get("location")), LocationResultDTO.class);

                    po.setLatitude(location.getLat());
                    po.setLongitude(location.getLng());
                    dealerInfoMapper.updateById(po);
                }
            } catch (Exception e) {
                logger.error("操作失败", e);

            }
        }

        return "success";
    }

    @GetMapping("/getCity")
    public String getCity() {
        LambdaQueryWrapper<DealerInfoPO> queryWrapper = new QueryWrapper<DealerInfoPO>().lambda();
        List<DealerInfoPO> list = dealerInfoMapper.selectList(queryWrapper);

        for (DealerInfoPO po : list) {
            try {
                if (StringUtils.isEmpty(po.getLatitude()) || StringUtils.isEmpty(po.getLongitude())) {
                    break;
                }

                String response = RestHttpUtil.get(restTemplate, URL2 + po.getLatitude() + "," + po.getLongitude(), String.class);
                HashMap jsonObject = JSON.parseObject(response, HashMap.class);
                HashMap result = JSON.parseObject(JSON.toJSONString(jsonObject.get("result")), HashMap.class);
                HashMap addressComponent = JSON.parseObject(JSON.toJSONString(result.get("addressComponent")), HashMap.class);
                String city = String.valueOf(addressComponent.get("city"));

                List<RegionVO> regionpolist = baseCommonRegionService.listAllData();
                regionpolist.stream().forEach(regionpo -> {
                    Integer type = regionpo.getRegionType();
                    RegionVO regionDto = new RegionVO();
                    regionDto.setRegionId(regionpo.getRegionId());
                    po.setCityId(Integer.parseInt(String.valueOf(regionpo.getRegionId())));
                });

            } catch (Exception e) {
                logger.error("操作失败", e);

            }
        }

        return "success";
    }
}
